<template>
  <div v-if="visible" class="custom-city-picker" :class="{ 'picker-closing': !showAnimation }">
    <div class="picker-overlay" @click="handleCancel"></div>
    <div class="picker-container" :class="{ 
      'picker-container--show': showAnimation,
      'picker-container--domestic': regionType === 'domestic',
      'picker-container--overseas': regionType === 'overseas'
    }">
      <!-- 头部 -->
      <div class="picker-header">
        <div class="picker-header-top">
          <div class="picker-header-left">
            <div class="picker-tabs">
              <button class="picker-tab" :class="{ 'picker-tab--active': regionType === 'domestic' }"
                @click="handleChangeRegionType('domestic')">
                国内
              </button>
              <button class="picker-tab" :class="{ 'picker-tab--active': regionType === 'overseas' }"
                @click="handleChangeRegionType('overseas')">
                海外
              </button>
            </div>
          </div>
          <button class="picker-btn picker-confirm" @click="handleConfirm">确定</button>
        </div>

        <!-- 搜索输入区域 -->
        <div class="quick-input-container">
          <div class="input-group">
            <div class="input-wrapper">
              <input 
                type="text" 
                class="datetime-input" 
                v-model="searchInput" 
                :placeholder="regionType === 'domestic' ? '搜索全国城市及地区' : '搜索海外国家及地区'"
                @input="handleSearchInput"
              />
              <button 
                class="clear-btn" 
                v-if="searchInput.length > 0" 
                type="button" 
                @click="clearSearchInput"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                    stroke-linejoin="round" />
                </svg>
              </button>
            </div>
          </div>

          <!-- 搜索结果列表 -->
          <div v-if="searchResults.length > 0" class="search-results-container">
            <div class="search-results-list">
              <div
                v-for="(result, index) in searchResults"
                :key="index"
                class="search-result-item"
                @click="selectSearchResult(result)"
              >
                <div class="search-result-text">{{ result.fullPath }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 选择器区域 - 国内模式（三列） -->
      <div class="picker-content" v-if="regionType === 'domestic'">
        <div class="picker-title">
          <span>省份</span>
          <span>城市</span>
          <span>区县</span>
        </div>

        <div class="picker-wheels" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
          @touchend="handleTouchEnd">
          <!-- 省份选择 -->
          <div class="picker-wheel" ref="provinceWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${provinceOffset}px)` }">
              <div v-for="(province, index) in provinces" :key="province.id" class="wheel-item"
                :class="{ 'wheel-item--active': selectedProvince?.id === province.id }" 
                @click="selectProvince(province)">
                {{ province.text }}
              </div>
            </div>
            <div class="picker-frame"></div>
          </div>

          <!-- 城市选择 -->
          <div class="picker-wheel" ref="cityWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${cityOffset}px)` }">
              <div v-for="(city, index) in cities" :key="city.id" class="wheel-item"
                :class="{ 'wheel-item--active': selectedCity?.id === city.id }" 
                @click="selectCity(city)">
                {{ city.text }}
              </div>
            </div>
            <div class="picker-frame"></div>
          </div>

          <!-- 区县选择 -->
          <div class="picker-wheel" ref="districtWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${districtOffset}px)` }">
              <div v-for="(district, index) in districts" :key="district.id" class="wheel-item"
                :class="{ 'wheel-item--active': selectedDistrict?.id === district.id }" 
                @click="selectDistrict(district)">
                {{ district.text }}
              </div>
            </div>
            <div class="picker-frame"></div>
          </div>
        </div>

        <!-- 整体遮罩层 -->
        <div class="picker-global-mask"></div>
      </div>

      <!-- 选择器区域 - 海外模式（两列） -->
      <div class="picker-content" v-if="regionType === 'overseas'">
        <div class="picker-title">
          <span>国家</span>
          <span>地区</span>
        </div>

        <div class="picker-wheels" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
          @touchend="handleTouchEnd">
          <!-- 国家选择 -->
          <div class="picker-wheel" ref="countryWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${countryOffset}px)` }">
              <div v-for="(country, index) in countries" :key="country.text" class="wheel-item"
                :class="{ 'wheel-item--active': selectedCountry?.text === country.text }" 
                @click="selectCountry(country)">
                {{ formatCountryDisplay(country) }}
              </div>
            </div>
            <div class="picker-frame"></div>
          </div>

          <!-- 地区选择 -->
          <div class="picker-wheel" ref="regionWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${regionOffset}px)` }">
              <div v-for="(region, index) in regions" :key="region.text" class="wheel-item"
                :class="{ 'wheel-item--active': selectedRegion?.text === region.text }" 
                @click="selectRegion(region)">
                {{ region.text }}
              </div>
            </div>
            <div class="picker-frame"></div>
          </div>
        </div>

        <!-- 整体遮罩层 -->
        <div class="picker-global-mask"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { AllCitys, overseasCitys } from './city_data'

// 数据接口定义
interface DomesticProvince {
  id: string
  text: string
  children?: DomesticCity[]
}

interface DomesticCity {
  id: string
  text: string
  children?: DomesticDistrict[]
}

interface DomesticDistrict {
  id: string
  text: string
  gisGcj02Lat?: number
  gisGcj02Lng?: number
}

interface OverseasCountry {
  text: string
  zone: number
  children?: OverseasRegion[]
  pinyin?: string
}

interface OverseasRegion {
  text: string
  zone: number
  lng?: number
}

// Props
interface Props {
  modelValue: boolean
  domesticData?: DomesticProvince[]
  overseasData?: OverseasCountry[]
  defaultRegion?: {
    type: 'domestic' | 'overseas'
    provinceId?: string
    cityId?: string
    districtId?: string
    country?: string
    region?: string
  }
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  domesticData: () => AllCitys,
  overseasData: () => overseasCitys
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [result: {
    type: 'domestic' | 'overseas'
    provinceId?: string
    cityId?: string
    districtId?: string
    provinceName?: string
    cityName?: string
    districtName?: string
    country?: string
    region?: string
    zone?: number
    lng?: number
    lat?: number
  }]
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 区域类型：domestic国内，overseas海外
const regionType = ref<'domestic' | 'overseas'>('domestic')

// 动画状态
const showAnimation = ref(false)

// 国内选择状态
const selectedProvince = ref<DomesticProvince | null>(null)
const selectedCity = ref<DomesticCity | null>(null)
const selectedDistrict = ref<DomesticDistrict | null>(null)

// 海外选择状态
const selectedCountry = ref<OverseasCountry | null>(null)
const selectedRegion = ref<OverseasRegion | null>(null)

// 轮盘引用
const provinceWheel = ref<HTMLElement>()
const cityWheel = ref<HTMLElement>()
const districtWheel = ref<HTMLElement>()
const countryWheel = ref<HTMLElement>()
const regionWheel = ref<HTMLElement>()

// 轮盘偏移量
const provinceOffset = ref(0)
const cityOffset = ref(0)
const districtOffset = ref(0)
const countryOffset = ref(0)
const regionOffset = ref(0)

// 轮盘高度
const ITEM_HEIGHT = 40

// 触摸相关
const touchStartY = ref(0)
const touchStartTime = ref(0)
const isDragging = ref(false)
const currentWheelIndex = ref(-1)

// 搜索相关
const searchInput = ref('')
const searchResults = ref<Array<{
  type: 'domestic' | 'overseas'
  province?: DomesticProvince
  city?: DomesticCity
  district?: DomesticDistrict
  country?: OverseasCountry
  region?: OverseasRegion
  displayText: string
  fullPath: string
}>>([])

// 计算属性：国内数据（优先使用 props，如果没有则使用默认数据）
const provinces = computed(() => {
  return props.domesticData && props.domesticData.length > 0 ? props.domesticData : AllCitys
})

const cities = computed(() => {
  if (!selectedProvince.value || !selectedProvince.value.children) {
    return []
  }
  return selectedProvince.value.children
})

const districts = computed(() => {
  if (!selectedCity.value || !selectedCity.value.children) {
    return []
  }
  return selectedCity.value.children
})

// 计算属性：海外数据（优先使用 props，如果没有则使用默认数据）
const countries = computed(() => {
  return props.overseasData && props.overseasData.length > 0 ? props.overseasData : overseasCitys
})

const regions = computed(() => {
  if (!selectedCountry.value || !selectedCountry.value.children) {
    return []
  }
  return selectedCountry.value.children
})

// 计算轮盘偏移量
const calculateOffset = (selectedIndex: number, totalItems: number) => {
  if (selectedIndex === -1 || totalItems === 0) return 0

  const visibleOptionNum = 5
  const baseOffset = ITEM_HEIGHT * (visibleOptionNum - 1) / 2
  const offset = baseOffset - (selectedIndex * ITEM_HEIGHT)

  return offset
}

// 更新所有轮盘位置
const updateAllWheelPositions = () => {
  if (regionType.value === 'domestic') {
    // 国内模式 - 使用对象引用查找，避免重复 id 问题
    let provinceIndex = -1
    const currentProvince = selectedProvince.value
    if (currentProvince) {
      provinceIndex = provinces.value.findIndex(p => p === currentProvince)
      // 如果找不到（对象引用不匹配），尝试用 id 查找
      if (provinceIndex === -1) {
        provinceIndex = provinces.value.findIndex(p => p.id === currentProvince.id)
      }
    }
    provinceOffset.value = calculateOffset(provinceIndex, provinces.value.length)

    let cityIndex = -1
    const currentCity = selectedCity.value
    if (currentCity) {
      cityIndex = cities.value.findIndex(c => c === currentCity)
      if (cityIndex === -1) {
        cityIndex = cities.value.findIndex(c => c.id === currentCity.id)
      }
    }
    cityOffset.value = calculateOffset(cityIndex, cities.value.length)

    let districtIndex = -1
    const currentDistrict = selectedDistrict.value
    if (currentDistrict) {
      districtIndex = districts.value.findIndex(d => d === currentDistrict)
      if (districtIndex === -1) {
        districtIndex = districts.value.findIndex(d => d.id === currentDistrict.id)
      }
    }
    districtOffset.value = calculateOffset(districtIndex, districts.value.length)
  } else {
    // 海外模式
    let countryIndex = -1
    const currentCountry = selectedCountry.value
    if (currentCountry) {
      countryIndex = countries.value.findIndex(c => c === currentCountry)
      if (countryIndex === -1) {
        countryIndex = countries.value.findIndex(c => c.text === currentCountry.text)
      }
    }
    countryOffset.value = calculateOffset(countryIndex, countries.value.length)

    let regionIndex = -1
    const currentRegion = selectedRegion.value
    if (currentRegion) {
      regionIndex = regions.value.findIndex(r => r === currentRegion)
      if (regionIndex === -1) {
        regionIndex = regions.value.findIndex(r => r.text === currentRegion.text)
      }
    }
    regionOffset.value = calculateOffset(regionIndex, regions.value.length)
  }
}

// 国内选择方法
const selectProvince = (province: DomesticProvince) => {
  selectedProvince.value = province
  selectedCity.value = null
  selectedDistrict.value = null
  
  // 如果省份有城市，自动选择第一个城市
  if (province.children && province.children.length > 0) {
    const firstCity = province.children[0]
    if (firstCity) {
      nextTick(() => {
        selectCity(firstCity)
      })
    } else {
      updateAllWheelPositions()
    }
  } else {
    updateAllWheelPositions()
  }
}

const selectCity = (city: DomesticCity) => {
  selectedCity.value = city
  selectedDistrict.value = null
  
  // 如果城市有区县，自动选择第一个区县
  if (city.children && city.children.length > 0) {
    const firstDistrict = city.children[0]
    if (firstDistrict) {
      nextTick(() => {
        selectDistrict(firstDistrict)
      })
    } else {
      updateAllWheelPositions()
    }
  } else {
    updateAllWheelPositions()
  }
}

const selectDistrict = (district: DomesticDistrict) => {
  selectedDistrict.value = district
  updateAllWheelPositions()
}

// 海外选择方法
const selectCountry = (country: OverseasCountry) => {
  selectedCountry.value = country
  selectedRegion.value = null
  
  // 如果国家有地区，自动选择第一个地区
  if (country.children && country.children.length > 0) {
    const firstRegion = country.children[0]
    if (firstRegion) {
      nextTick(() => {
        selectRegion(firstRegion)
      })
    } else {
      updateAllWheelPositions()
    }
  } else {
    updateAllWheelPositions()
  }
}

const selectRegion = (region: OverseasRegion) => {
  selectedRegion.value = region
  updateAllWheelPositions()
}

// 格式化国家显示 - 显示为"国家 GMT+X"格式
const formatCountryDisplay = (country: OverseasCountry): string => {
  const zone = country.zone
  const zoneSign = zone >= 0 ? '+' : ''
  return `${country.text} GMT${zoneSign}${zone}`
}

// 搜索功能
const handleSearchInput = () => {
  const query = searchInput.value.trim().toLowerCase()
  searchResults.value = []

  if (!query) {
    return
  }

  if (regionType.value === 'domestic') {
    // 国内模式：搜索省份、城市、区县
    const dataToSearch = provinces.value
    if (!dataToSearch || dataToSearch.length === 0) {
      return
    }
    
    dataToSearch.forEach(province => {
      // 搜索省份
      if (province.text.toLowerCase().includes(query)) {
        searchResults.value.push({
          type: 'domestic',
          province,
          displayText: province.text,
          fullPath: province.text
        })
      }

      // 搜索城市
      province.children?.forEach(city => {
        if (city.text.toLowerCase().includes(query)) {
          searchResults.value.push({
            type: 'domestic',
            province,
            city,
            displayText: city.text,
            fullPath: `${province.text} ${city.text}`
          })
        }

        // 搜索区县
        city.children?.forEach(district => {
          if (district.text.toLowerCase().includes(query)) {
            searchResults.value.push({
              type: 'domestic',
              province,
              city,
              district,
              displayText: district.text,
              fullPath: `${province.text} ${city.text} ${district.text}`
            })
          }
        })
      })
    })
  } else {
    // 海外模式：搜索国家、地区
    const dataToSearch = countries.value
    if (!dataToSearch || dataToSearch.length === 0) {
      return
    }
    
    dataToSearch.forEach(country => {
      const countryDisplay = formatCountryDisplay(country)
      // 搜索国家名称
      if (country.text.toLowerCase().includes(query) || 
          countryDisplay.toLowerCase().includes(query)) {
        searchResults.value.push({
          type: 'overseas',
          country,
          displayText: countryDisplay,
          fullPath: countryDisplay
        })
      }

      // 搜索地区
      country.children?.forEach(region => {
        if (region.text.toLowerCase().includes(query)) {
          searchResults.value.push({
            type: 'overseas',
            country,
            region,
            displayText: region.text,
            fullPath: `${countryDisplay} ${region.text}`
          })
        }
      })
    })
  }

  // 限制搜索结果数量
  if (searchResults.value.length > 50) {
    searchResults.value = searchResults.value.slice(0, 50)
  }
}

// 清空搜索
const clearSearchInput = () => {
  searchInput.value = ''
  searchResults.value = []
}

// 选择搜索结果
const selectSearchResult = (result: typeof searchResults.value[0]) => {
  if (result.type === 'domestic') {
    // 国内模式
    if (result.district && result.province && result.city) {
      // 选择了区县，需要先选择省份和城市
      selectedProvince.value = result.province
      selectedCity.value = result.city
      selectedDistrict.value = result.district
      updateAllWheelPositions()
    } else if (result.city && result.province) {
      // 选择了城市，需要先选择省份
      selectedProvince.value = result.province
      selectCity(result.city)
    } else if (result.province) {
      // 选择了省份
      selectProvince(result.province)
    }
  } else {
    // 海外模式
    if (result.region && result.country) {
      // 选择了地区，需要先选择国家
      selectedCountry.value = result.country
      selectRegion(result.region)
    } else if (result.country) {
      // 选择了国家
      selectCountry(result.country)
    }
  }
  
  // 清空搜索
  clearSearchInput()
}

// 获取当前索引 - 统一的索引查找方法
const getCurrentIndex = (items: any[], currentValue: any, offset: number | undefined): number => {
  // 方法1: 使用对象引用直接查找（最可靠）
  if (currentValue) {
    const refIndex = items.findIndex(item => item === currentValue)
    if (refIndex !== -1) {
      return refIndex
    }
  }

  // 方法2: 根据偏移量计算索引
  if (offset !== undefined) {
    const visibleOptionNum = 5
    const baseOffset = ITEM_HEIGHT * (visibleOptionNum - 1) / 2
    const calculatedIndex = Math.round((baseOffset - offset) / ITEM_HEIGHT)
    return Math.max(0, Math.min(items.length - 1, calculatedIndex))
  }

  // 方法3: 默认返回第一个索引
  return 0
}

// 触摸事件处理
const handleTouchStart = (e: TouchEvent) => {
  const touch = e.touches[0]
  if (!touch) return

  // 记录触摸开始时所在的轮盘索引
  const target = e.target as HTMLElement
  let wheel = target.closest('.picker-wheel')
  
  // 如果找不到轮盘，尝试根据触摸位置计算轮盘索引
  if (!wheel) {
    const wheelsContainer = target.closest('.picker-wheels')
    if (wheelsContainer) {
      const wheels = Array.from(wheelsContainer.children).filter(el => el.classList.contains('picker-wheel')) as HTMLElement[]
      const touchX = touch.clientX
      
      // 根据触摸位置确定是哪个轮盘
      for (let i = 0; i < wheels.length; i++) {
        const currentWheel = wheels[i]
        if (currentWheel) {
          const wheelRect = currentWheel.getBoundingClientRect()
          if (touchX >= wheelRect.left && touchX <= wheelRect.right) {
            wheel = currentWheel
            break
          }
        }
      }
    }
  }
  
  if (wheel && wheel.parentElement) {
    const wheels = Array.from(wheel.parentElement.children).filter(el => el.classList.contains('picker-wheel'))
    currentWheelIndex.value = wheels.indexOf(wheel)
  } else {
    currentWheelIndex.value = -1
  }

  touchStartY.value = touch.clientY
  touchStartTime.value = Date.now()
  isDragging.value = true
}

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return
  e.preventDefault()
}

const handleTouchEnd = (e: TouchEvent) => {
  if (!isDragging.value) return

  isDragging.value = false
  const deltaTime = Date.now() - touchStartTime.value
  const changedTouch = e.changedTouches[0]
  if (!changedTouch) return

  const deltaY = changedTouch.clientY - touchStartY.value

  // 只有滑动距离超过阈值才处理
  if (Math.abs(deltaY) > 10) {
    // 使用触摸开始时记录的轮盘索引，确保准确性
    const wheelIndex = currentWheelIndex.value
    if (wheelIndex >= 0) {
      handleWheelSwipe(wheelIndex, deltaY, deltaTime)
    }
  }
  
  // 重置轮盘索引
  currentWheelIndex.value = -1
}

// 统一的滑动处理函数
const handleWheelSwipe = (wheelIndex: number, deltaY: number, deltaTime: number) => {
  if (regionType.value === 'domestic') {
    handleDomesticSwipe(wheelIndex, deltaY, deltaTime)
  } else {
    handleOverseasSwipe(wheelIndex, deltaY, deltaTime)
  }
}

// 国内模式滑动处理
const handleDomesticSwipe = (wheelIndex: number, deltaY: number, deltaTime: number) => {
  const wheels = [provinces.value, cities.value, districts.value]
  const currentValues = [selectedProvince.value, selectedCity.value, selectedDistrict.value]
  const offsets = [provinceOffset.value, cityOffset.value, districtOffset.value]
  const selectors = [selectProvince, selectCity, selectDistrict]

  if (wheelIndex < 0 || wheelIndex >= wheels.length) return

  const items = wheels[wheelIndex]
  const currentValue = currentValues[wheelIndex]
  const offset = offsets[wheelIndex]

  if (!items || items.length === 0) return

  // 获取当前索引
  const currentIndex = getCurrentIndex(items, currentValue, offset)

  // 计算步数 - 优化轻微滑动
  let stepCount = 1
  const absDeltaY = Math.abs(deltaY)
  
  if (deltaTime < 200) {
    // 快速滑动，步数基于滑动距离
    stepCount = Math.max(1, Math.min(absDeltaY / 30, 5))
  } else if (deltaTime < 500) {
    // 中等速度滑动
    stepCount = Math.max(1, Math.min(absDeltaY / 50, 3))
  } else {
    // 慢速滑动，轻微滑动也要响应
    stepCount = absDeltaY > 10 ? 1 : 0
  }

  // 如果步数为0但滑动距离足够，确保至少移动1步（用于轻微滑动）
  if (stepCount === 0 && absDeltaY > 10) {
    stepCount = 1
  }

  // 计算新索引
  const direction = deltaY > 0 ? -1 : 1
  const newIndex = Math.max(0, Math.min(items.length - 1, currentIndex + (direction * Math.round(stepCount))))

  // 只有索引改变才更新（确保轻微滑动也能触发）
  if (newIndex !== currentIndex && newIndex >= 0 && newIndex < items.length) {
    const newValue = items[newIndex]
    const selector = selectors[wheelIndex]
    
    if (newValue && selector) {
      // 调用对应的选择函数
      if (wheelIndex === 0) {
        selector(newValue as DomesticProvince)
      } else if (wheelIndex === 1) {
        selector(newValue as DomesticCity)
      } else if (wheelIndex === 2) {
        selector(newValue as DomesticDistrict)
      }
    }
  }
}

// 海外模式滑动处理
const handleOverseasSwipe = (wheelIndex: number, deltaY: number, deltaTime: number) => {
  const wheels = [countries.value, regions.value]
  const currentValues = [selectedCountry.value, selectedRegion.value]
  const offsets = [countryOffset.value, regionOffset.value]
  const selectors = [selectCountry, selectRegion]

  if (wheelIndex < 0 || wheelIndex >= wheels.length) return

  const items = wheels[wheelIndex]
  const currentValue = currentValues[wheelIndex]
  const offset = offsets[wheelIndex]

  if (!items || items.length === 0) return

  // 获取当前索引
  const currentIndex = getCurrentIndex(items, currentValue, offset)

  // 计算步数 - 优化轻微滑动
  let stepCount = 1
  const absDeltaY = Math.abs(deltaY)
  
  if (deltaTime < 200) {
    // 快速滑动，步数基于滑动距离
    stepCount = Math.max(1, Math.min(absDeltaY / 30, 5))
  } else if (deltaTime < 500) {
    // 中等速度滑动
    stepCount = Math.max(1, Math.min(absDeltaY / 50, 3))
  } else {
    // 慢速滑动，轻微滑动也要响应
    stepCount = absDeltaY > 10 ? 1 : 0
  }

  // 如果步数为0但滑动距离足够，确保至少移动1步（用于轻微滑动）
  if (stepCount === 0 && absDeltaY > 10) {
    stepCount = 1
  }

  // 计算新索引
  const direction = deltaY > 0 ? -1 : 1
  const newIndex = Math.max(0, Math.min(items.length - 1, currentIndex + (direction * Math.round(stepCount))))

  // 只有索引改变才更新（确保轻微滑动也能触发）
  if (newIndex !== currentIndex && newIndex >= 0 && newIndex < items.length) {
    const newValue = items[newIndex]
    const selector = selectors[wheelIndex]
    
    if (newValue && selector) {
      // 调用对应的选择函数
      if (wheelIndex === 0) {
        selector(newValue as OverseasCountry)
      } else if (wheelIndex === 1) {
        selector(newValue as OverseasRegion)
      }
    }
  }
}

// 区域类型切换
const handleChangeRegionType = (type: 'domestic' | 'overseas') => {
  regionType.value = type
  
  // 切换类型时清空搜索
  clearSearchInput()
  
  // 重置选择
  if (type === 'domestic') {
    selectedCountry.value = null
    selectedRegion.value = null
    
    // 初始化第一个省份
    if (provinces.value.length > 0) {
      const firstProvince = provinces.value[0]
      if (firstProvince) {
        // 直接选择，不使用 nextTick，确保立即更新
        selectProvince(firstProvince)
        // 确保位置更新
        nextTick(() => {
          updateAllWheelPositions()
        })
      } else {
        selectedProvince.value = null
        selectedCity.value = null
        selectedDistrict.value = null
        updateAllWheelPositions()
      }
    } else {
      selectedProvince.value = null
      selectedCity.value = null
      selectedDistrict.value = null
      updateAllWheelPositions()
    }
  } else {
    selectedProvince.value = null
    selectedCity.value = null
    selectedDistrict.value = null
    
    // 初始化第一个国家
    if (countries.value.length > 0) {
      const firstCountry = countries.value[0]
      if (firstCountry) {
        nextTick(() => {
          selectCountry(firstCountry)
        })
      } else {
        selectedCountry.value = null
        selectedRegion.value = null
        updateAllWheelPositions()
      }
    } else {
      selectedCountry.value = null
      selectedRegion.value = null
      updateAllWheelPositions()
    }
  }
}

// 初始化默认值
const initializeValues = () => {
  if (props.defaultRegion) {
    regionType.value = props.defaultRegion.type
    
    if (props.defaultRegion.type === 'domestic') {
      // 查找并选择默认的省份、城市、区县
      const province = provinces.value.find(p => p.id === props.defaultRegion?.provinceId)
      if (province) {
        selectedProvince.value = province
        const city = province.children?.find(c => c.id === props.defaultRegion?.cityId)
        if (city) {
          selectedCity.value = city
          const district = city.children?.find(d => d.id === props.defaultRegion?.districtId)
          if (district) {
            selectedDistrict.value = district
          } else if (city.children && city.children.length > 0) {
            // 如果没有找到指定的区县，选择第一个
            const firstDistrict = city.children[0]
            if (firstDistrict) {
              selectedDistrict.value = firstDistrict
            }
          }
        } else if (province.children && province.children.length > 0) {
          // 如果没有找到指定的城市，选择第一个
          const firstCity = province.children[0]
          if (firstCity) {
            selectCity(firstCity)
          }
        }
        // 确保位置更新
        nextTick(() => {
          updateAllWheelPositions()
        })
      } else if (provinces.value.length > 0) {
        // 如果没有找到指定的省份，选择第一个
        const firstProvince = provinces.value[0]
        if (firstProvince) {
          selectProvince(firstProvince)
        }
      } else {
        updateAllWheelPositions()
      }
    } else {
      // 查找并选择默认的国家、地区
      const country = countries.value.find(c => c.text === props.defaultRegion?.country)
      if (country) {
        selectedCountry.value = country
        const region = country.children?.find(r => r.text === props.defaultRegion?.region)
        if (region) {
          selectedRegion.value = region
        } else if (country.children && country.children.length > 0) {
          // 如果没有找到指定的地区，选择第一个
          const firstRegion = country.children[0]
          if (firstRegion) {
            selectedRegion.value = firstRegion
          }
        }
        // 确保位置更新
        nextTick(() => {
          updateAllWheelPositions()
        })
      } else if (countries.value.length > 0) {
        // 如果没有找到指定的国家，选择第一个
        const firstCountry = countries.value[0]
        if (firstCountry) {
          selectCountry(firstCountry)
        }
      } else {
        updateAllWheelPositions()
      }
    }
  } else {
    // 没有默认值，初始化第一个选项
    if (regionType.value === 'domestic' && provinces.value.length > 0) {
      const firstProvince = provinces.value[0]
      if (firstProvince) {
        // 直接选择，不使用 nextTick，确保立即更新
        selectProvince(firstProvince)
        // 确保位置更新
        nextTick(() => {
          updateAllWheelPositions()
        })
      } else {
        updateAllWheelPositions()
      }
    } else if (regionType.value === 'overseas' && countries.value.length > 0) {
      const firstCountry = countries.value[0]
      if (firstCountry) {
        selectCountry(firstCountry)
        nextTick(() => {
          updateAllWheelPositions()
        })
      } else {
        updateAllWheelPositions()
      }
    } else {
      updateAllWheelPositions()
    }
  }
}

// 处理确认
const handleConfirm = () => {
  if (regionType.value === 'domestic') {
    // 国内模式：需要选择省份、城市、区县
    if (!selectedProvince.value || !selectedCity.value || !selectedDistrict.value) {
      return
    }
    
    const result = {
      type: 'domestic' as const,
      provinceId: selectedProvince.value.id,
      cityId: selectedCity.value.id,
      districtId: selectedDistrict.value.id,
      provinceName: selectedProvince.value.text,
      cityName: selectedCity.value.text,
      districtName: selectedDistrict.value.text,
      // 只返回单独的经纬度字段，不返回数组
      lat: selectedDistrict.value.gisGcj02Lat,
      lng: selectedDistrict.value.gisGcj02Lng
    }
    
    emit('confirm', result)
  } else {
    // 海外模式：需要选择国家和地区
    if (!selectedCountry.value || !selectedRegion.value) {
      return
    }
    
    const result = {
      type: 'overseas' as const,
      country: selectedCountry.value.text,
      region: selectedRegion.value.text,
      zone: selectedRegion.value.zone || selectedCountry.value.zone,
      // 只返回单独的经度字段，不返回数组
      lng: selectedRegion.value.lng
    }
    
    emit('confirm', result)
  }
  
  // 先播放收起动画
  showAnimation.value = false
  // 延迟关闭，等待动画完成
  setTimeout(() => {
    visible.value = false
  }, 300)
}

// 处理取消
const handleCancel = () => {
  // 先播放收起动画
  showAnimation.value = false
  // 延迟关闭，等待动画完成
  setTimeout(() => {
    visible.value = false
  }, 300)
}

// 键盘事件处理
const handleKeydown = (e: KeyboardEvent) => {
  if (!visible.value) return

  switch (e.key) {
    case 'Escape':
      handleCancel()
      break
    case 'Enter':
      handleConfirm()
      break
  }
}

onMounted(() => {
  if (visible.value) {
    document.addEventListener('keydown', handleKeydown)
  }
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 监听弹窗显示
watch(visible, (newVal) => {
  if (newVal) {
    initializeValues()
    document.body.style.overflow = 'hidden'
    document.addEventListener('keydown', handleKeydown)
    // 延迟触发动画，确保DOM已渲染
    setTimeout(() => {
      showAnimation.value = true
    }, 50)
  } else {
    showAnimation.value = false
    document.body.style.overflow = ''
    document.removeEventListener('keydown', handleKeydown)
  }
})

// 监听数据变化，更新轮盘位置
watch([selectedProvince, selectedCity, selectedDistrict, selectedCountry, selectedRegion, regionType], () => {
  nextTick(() => {
    updateAllWheelPositions()
  })
})
</script>

<style scoped>
.custom-city-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.picker-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 1;
  transition: opacity 0.3s ease-out;
  z-index: 1;
}

.custom-city-picker .picker-overlay {
  opacity: 1;
}

.custom-city-picker.picker-closing .picker-overlay {
  opacity: 0;
}

.picker-container {
  position: relative;
  width: 100%;
  background: #ffffff;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94), height 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.2);
  z-index: 2;
}

.picker-container--show {
  transform: translateY(0);
}

/* 不同tab模式的高度动画 */
.picker-container--domestic {
  height: 450px;
}

.picker-container--overseas {
  height: 450px;
}

.picker-header {
  display: flex;
  flex-direction: column;
  padding: 24px 12px 12px 12px;
  border-bottom: 1px solid #f1f5f9;
  flex-shrink: 0;
  background: #ffffff;
  position: relative;
  z-index: 4;
}

.picker-header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.picker-btn {
  background: none;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  height: 40px;
  padding: 0 20px;
  border-radius: 20px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

.picker-confirm {
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  color: #d4af37;
  border: none;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.picker-confirm:hover {
  background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
  color: #f4d03f;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

.picker-header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.picker-tabs {
  display: flex;
  background: #fafbfc;
  border-radius: 24px;
  padding: 1px;
  border: 1px solid #f1f5f9;
  height: 44px;
  min-width: 160px;
}

.picker-tab {
  flex: 1;
  height: 36px;
  padding: 0 24px;
  background: none;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #94a3b8;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picker-tab--active {
  background: #ffffff;
  color: #1e293b;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
}

.picker-content {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 300px;
  transition: height 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.picker-title {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.picker-title span {
  flex: 1;
  text-align: center;
}

.picker-wheels {
  display: flex;
  flex: 1;
  overflow: hidden;
  position: relative;
  height: 200px;
}

.picker-wheel {
  flex: 1;
  height: 200px;
  position: relative;
  overflow: hidden;
  background: transparent;
}

.wheel-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transition: transform 0.3s ease-out;
}

.wheel-item {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #1e293b;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  font-size: 14px;
}

.wheel-item:hover {
  color: #1e293b;
}

.wheel-item--active {
  color: #1e293b;
  font-weight: bold;
  font-size: 18px;
}

.picker-frame {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 40px;
  transform: translateY(-50%);
  background: rgba(59, 130, 246, 0.05);
  pointer-events: none;
  z-index: 2;
}

.picker-global-mask {
  position: absolute;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom,
      rgba(255, 255, 255, 0.8) 0%,
      rgba(255, 255, 255, 0.3) 20%,
      rgba(255, 255, 255, 0) 50%,
      rgba(255, 255, 255, 0) 50%,
      rgba(255, 255, 255, 0.3) 80%,
      rgba(255, 255, 255, 0.8) 100%);
  pointer-events: none;
  z-index: 3;
}

/* 快速输入区域 */
.quick-input-container {
  width: 100%;
}

.input-group {
  display: flex;
  gap: 8px;
  align-items: center;
  background: #f1f5f9;
  border: 1px solid #f1f5f9;
  border-radius: 24px;
  padding: 4px;
}

.input-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.datetime-input {
  flex: 1;
  height: 36px;
  padding: 0 40px 0 16px;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  color: #1e293b;
  background: transparent;
  transition: all 0.2s ease;
}

.datetime-input:focus {
  outline: none;
  background: transparent;
}

.datetime-input::placeholder {
  color: #94a3b8;
  font-size: 12px;
}

.clear-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  border: none;
  background: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  transition: color 0.2s ease;
  z-index: 1;
}

.clear-btn:hover {
  color: #64748b;
}

.clear-btn:active {
  color: #475569;
}

/* 搜索结果列表 */
.search-results-container {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  right: 0;
  /* 计算最大高度：根据弹出框高度限制
   * 国内模式：450px - 头部(~120px) - 搜索框(~60px) - 标题(~44px) - 轮盘最小显示(~200px) = ~26px
   * 海外模式：400px - 头部(~120px) - 搜索框(~60px) - 标题(~44px) - 轮盘最小显示(~200px) = -24px
   * 为了不影响选择器显示，限制最大高度为 200px，超出部分滚动
   */
  max-height: 200px;
  overflow-y: auto;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 100;
  margin: 0 20px;
  width: calc(100% - 40px);
}

.search-results-list {
  display: flex;
  flex-direction: column;
}

.search-result-item {
  padding: 12px 20px;
  border-bottom: 1px solid #f1f5f9;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #ffffff;
}

.search-result-item:hover {
  background: #f8fafc;
  border-bottom-color: #e2e8f0;
}

.search-result-item:last-child {
  border-bottom: none;
}

.search-result-text {
  font-size: 14px;
  color: #1e293b;
  font-weight: 500;
}
</style>
